package uestc.lj.gulishop.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import uestc.lj.common.exception.ErrorCode;
import uestc.lj.common.utils.R;

/**
 * sentinel对于网关的回调
 *
 * @Author:Crazlee
 * @Date:2021/6/25
 */
@Configuration
public class SentinelGatewayConfig {
    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            /**
             * 网关被限流之后就会调用此回调
             * @param exchange
             * @param t
             * @return
             */
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                R error = R.error(ErrorCode.SYSTEM_BUZY_NOW.getCode(), ErrorCode.SYSTEM_BUZY_NOW.getMessage());
                String errorJSON = JSON.toJSONString(error);
                return ServerResponse.ok().body(Mono.just(error), String.class);
            }
        });
    }
}
